import axios from 'axios'
import io from 'socket.io-client'
const socket = io('ws://localhost:9093')

// 获取聊天列表
const MSG_LIST = 'MSG_LIST'
// 读取信息
const MSG_RECV = 'MSG_RECV'
// 标识已读
const MSG_READ = 'MSG_READ'

const initState = {
  chatmsg:[],
  users:{},
  unread:0
}

export function chat(state=initState, action){
  switch(action.type){
    case MSG_LIST:
      return {...state,users:action.payload.users, chatmsg:action.payload.data,unread:action.payload.data.filter(v=>!v.read&&v.to===action.payload.userid).length}
    case MSG_RECV:
      const n = action.payload.to === action.userid ? 1:0
      return {...state, chatmsg: [...state.chatmsg, action.payload],unread:state.unread+n}
    case MSG_READ:
      const {from, num} = action.payload
      return {...state, chatmsg: state.chatmsg.map(v=>({...v, read:from === v.from ? true : v.read})), unread: state.unread - num}
      // return {...state, chatmsg: state.chatmsg.map(v=>{
      //   return v.chatid === action.payload ? readItem(v) : v
      // })}
    default:
      return state
  }
}

function readItem(v){
  v.read = true
  return v
}
function msgList(data, users, userid){
  return {type: 'MSG_LIST', payload: {data,users,userid}}
}

function msgRecv(msg, userid) {
  return {type:MSG_RECV, userid,payload: msg}
}
// function msgRead(chatid){
//   return {type: MSG_READ, payload:chatid}
// }


export function getMsgList(){
  return (dispatch, getState)=>{
    axios.get('/user/getmsglist')
      .then(res=>{
        const userid = getState().user._id
        if (res.status === 200 && res.data.code===0){
          dispatch(msgList(res.data.msgs, res.data.users, userid))
        }
      })
  }
}


export function recvMsg(){
  return (dispatch,getState)=>{
    socket.on('recvmsg', function(data){
      console.log(data)
      const userid = getState().user._id
      dispatch(msgRecv(data,userid))
    })
  }
}
export function sendMsg({from, to, msg}){
  return dispatch=>{
    socket.emit('sendmsg', {from, to, msg})
  }
}

export function messageRead(chatid){
  return dispatch=>{
    dispatch(msgRead(chatid))
  }
}
function msgRead({from, userid, num}){
  return {type: MSG_READ, payload: {from, userid, num}}
}
export function readMsg(from){
  return (dispatch, getState) => {
    axios.post('/user/readmsg',{from})
      .then(res => {
        const userid = getState().user._id
        if (res.state === 200 && res.data.code === 0){
          dispatch(msgRead({userid, from, num:res.data.num}))
        }
    })
  }
}